<template>
  <div class="card-setting-container">
    <div class="left-box">
      <SectionTitle title="卡片字段配置" style="margin: 12px 0"/>
      <div class="field-group">
        <template v-for="(item, index) in cardFields" >
          <div :key="item.key + Math.floor(Math.random() * 10000) + index" class="field-item">
            <div class="check"><el-checkbox v-model="item.isCheck" @change="handleCheckChange($event, item)" /></div>
            <div :style="{'fontWeight': item.isCheck ? 'bold' : ''}" class="field-content">
              <ToolTip :content="item.subformFullName || item.name" />
            </div>
          </div>
        </template>
      </div>
    </div>
    <div class="middle-box">
      <CardList v-model="cardConfigsData" :active-key="activeKey" value-key="defaultValue" is-configuring @onFieldClick="handleFieldClick"/>
      <div class="card-action-btns flex-center">
        <div class="flex-center">
          <span style="margin-right: 4px; font-size: 14px; font-weight: bold; white-space: nowrap;">启用卡片</span>
          <el-switch v-model="cardConfigsData.isEnable" @change="handleCardEnableChange" />
        </div>
        <el-button type="primary" size="small" @click="handlePreview">预览卡片</el-button>
      </div>
    </div>
    <div class="right-box">
      <CardConfigs
        ref="cardConfigsRefs"
        v-model="cardConfigsData"
        :active-key="activeKey"
        :form-list="formList"
        :card-fields="cardFields"
        @updateCardFields="updateCardFields"
        @activeKeyChange="handleFieldClick"/>
    </div>
    <CardListPreview ref="cardListPreviewRef" />
  </div>
</template>

<script>
import SectionTitle from '@/components/Title';
import CardList from './cardList';
import CardConfigs from './cardConfigs';
import CardListPreview from './cardListPreview';
import { forEachFormOptions } from '@/utils/formMakeUtils';
import { EventBus } from '@/utils/eventBus';
import { allTargets, cardFieldTargets } from './settingTargets';
export default {
  name: 'CardSetting',
  components: {
    CardList,
    SectionTitle,
    CardListPreview,
    CardConfigs
  },
  model: {
    prop: 'cardConfigsData',
    event: 'change'
  },
  props: {
    formList: {
      type: Array,
      default: () => []
    },
    cardConfigsData: {
      type: Object,
      default: () => ({
        width: '400',
        minWidth: '',
        maxWidth: '',
        height: '',
        minHeight: '',
        maxHeight: '',
        options: [],
        isEnable: false
      })
    }
  },
  data() {
    return {
      activeKey: '',
      cardStatus: false,
      cardFields: [
        { key: 'creatorAvatar', name: '头像' },
        { key: 'status', name: '状态' },
        { key: 'currentNode', name: '当前节点' },
        { key: 'currentHandler', name: '当前处理人' },
        { key: 'divider', name: '分割线' }
      ]
    };
  },
  watch: {
    cardConfigsData: {
      handler() {
        this.statusCheck();
      },
      deep: true
    }
  },
  created() {
    EventBus.$on('formOptionsChange', configObj => {
      this.formListChange(this.formList);
    });
    this.statusCheck();
  },
  methods: {
    // 初始化列表字段
    initList(formList) {
      const fields = this.getList(_.cloneDeep(formList));
      this.$set(this, 'cardFields', fields);
      this.$refs['cardConfigsRefs'].configType = '0';
      this.$emit('change', {
        width: '400',
        minWidth: '',
        maxWidth: '',
        height: '',
        minHeight: '',
        maxHeight: '',
        options: [],
        isEnable: false
      });
    },
    statusCheck() {
      this.validate().then(() => {
        this.cardStatus = false;
        this.$emit('statusCheck');
        this.$emit('updateCardDot', this.cardStatus);
      }).catch(() => {
        this.cardStatus = true;
        this.$emit('statusCheck');
        this.$emit('updateCardDot', this.cardStatus);
      });
    },
    validate(isPreview = false) {
      return new Promise((resolve, reject) => {
        if (!isPreview && (!this.cardConfigsData.isEnable || !this.cardConfigsData.options.length)) {
          resolve(true);
          return;
        }
        if (!this.cardConfigsData.width) {
          reject('请设置卡片视图配置-卡片配置的宽度');
          return;
        }
        this.cardConfigsData.options.forEach(item => {
          if (['creatorAvatar'].includes(item.key)) {
            if (!item.gridType) {
              reject(`请设置卡片视图配置-字段【${item.name}】的所占位栅格数`);
            } else if (!item.userLinkKey) {
              reject(`请设置卡片视图配置-字段【${item.name}】的头像取值`);
            }
          } else if (!['richEditor', 'upAttachment'].includes(item.type)) {
            if (!item.fontLength) {
              reject(`请设置卡片视图配置-字段【${item.name}】的显示字符长度`);
            } else if (!item.fontSize) {
              reject(`请设置卡片视图配置-字段【${item.name}】的字体大小`);
            } else if (!item.gridType) {
              reject(`请设置卡片视图配置-字段【${item.name}】的所占位栅格数`);
            } else if (!item.fontColor) {
              reject(`请设置卡片视图配置-字段【${item.name}】的文字颜色`);
            } else if (item.showType === 'tag' && !item.tagColor) {
              reject(`请设置卡片视图配置-字段【${item.name}】的标签填充颜色`);
            }
          }
        });
        resolve(true);
      });
    },
    handleCardEnableChange(status) {
      if (status && !this.cardConfigsData.options.length) {
        this.$message.warning('请至少选择一个字段生成卡片');
        this.cardConfigsData.isEnable = false;
      } else {
        this.statusCheck();
      }
    },
    updateCardFields(item, isDel = false) {
      if (isDel) {
        const fieldIndex = this.cardFields.findIndex(field => field.key === item.key);
        fieldIndex !== -1 && this.cardFields.splice(fieldIndex, 1);
      } else {
        this.cardFields.push(item);
      }
    },
    handlePreview() {
      this.validate(true).then(() => {
        this.$refs['cardListPreviewRef'].open(this.cardConfigsData);
      }).catch((msg) => {
        this.$message.error(msg);
      });
    },
    handleCardEnable() {
      this.cardConfigsData.isEnable = !this.cardConfigsData.isEnable;
    },
    getData() {
      return {
        fields: _.cloneDeep(this.cardFields),
        configs: _.cloneDeep(this.cardConfigsData)
      };
    },
    setData(cardSetting) {
      if (!cardSetting) {
        this.initList(this.formList);
      } else {
        this.cardFields = _.cloneDeep(cardSetting.fields);
        cardSetting.configs.options.map(el => {
          if (!el.margin) {
            el.margin = { top: 0, bottom: 0 };
          }
          if (!el.padding) {
            el.padding = { top: 0, bottom: 0, left: 0, right: 0 };
          }
          if (typeof el.radius !== 'object') {
            el.radius = { topLeft: 0, topRight: 0, bottomLeft: 0, bottomRight: 0 };
          }
        });
        this.$emit('change', _.cloneDeep(cardSetting.configs));
        // v3.6.3 新增分割线配置，历史数据处理
        if (this.cardFields.every(item => item.key !== 'divider')) {
          this.cardFields.push({ key: 'divider', name: '分割线', isCheck: false });
        }
      }
    },
    formListChange: _.debounce(function(formList) {
      let oldListFields = _.cloneDeep(this.cardFields);
      // 复制的分割线特殊处理,需要在处理后再加入结果中，分割线来源不属于表单设计拖拽，会被覆盖
      const dividerCopyArr = oldListFields.filter(item => item.key !== 'divider' && item.key.startsWith('divider'));
      const newListFields = this.getList(_.cloneDeep(formList));
      const deletedArr = _.differenceBy(oldListFields, newListFields, 'key');
      const addArr = _.differenceBy(newListFields, oldListFields, 'key');

      if (deletedArr.length) {
        // 删除
        _.pullAllBy(oldListFields, deletedArr, 'key');
      }
      if (addArr.length) {
        // 添加
        oldListFields = _.concat(addArr, oldListFields);
      }
      // 修改名称
      oldListFields.forEach(i => {
        const temp = newListFields.find(j => j.key === i.key);
        if (temp) {
          i.subformFullName = temp.subformFullName;
          i.name = temp.name;
          i.type = temp.type;
          if (this.cardConfigsData.options && this.cardConfigsData.options.length) {
            const findIndex = this.cardConfigsData.options.findIndex(j => j.key === i.key);
            findIndex > -1 && (this.cardConfigsData.options[findIndex] = Object.assign(this.cardConfigsData.options[findIndex], { name: temp.name, type: temp.type }));
            if (deletedArr.length) { // 表单设计移除字段后卡片配置同步移除
              const delArr = deletedArr.filter(i => i.key !== 'divider' && !i.key.startsWith('divider'));
              this.cardConfigsData.options = this.cardConfigsData.options.filter(item => !delArr.map(i => i.key).includes(item.key));
            }
          }
        }
      });
      this.$set(this, 'cardFields', [...oldListFields, ...dividerCopyArr]);
    }, 200),
    getList(formList) {
      const listFieldTemp = [
        { key: 'creatorAvatar', name: '头像' },
        { key: 'status', name: '状态' },
        { key: 'currentNode', name: '当前节点' },
        { key: 'currentHandler', name: '当前处理人' },
        { key: 'divider', name: '分割线' }
      ];
      const result = [];
      forEachFormOptions(formList, item => {
        if (cardFieldTargets.includes(item.type)) {
          if (item.type === 'subform') {
            if (Array.isArray(item.subform) && item.subform.length) {
              item.subform.forEach(i => {
                if (allTargets.includes(i.type)) {
                  i.subformFullName = item.name + '.' + i.name;
                }
              });
              result.push(...item.subform.filter(i => allTargets.includes(i.type)));
            }
          } else {
            result.push(item);
          }
        }
      }, { notForEachSubform: true });
      return [...result, ...listFieldTemp];
    },
    handleFieldClick(key) {
      this.$refs['cardConfigsRefs'].configType = '1';
      this.activeKey = key;
    },
    handleCheckChange(status, data) {
      if (status) {
        this.cardConfigsData.options.push({
          ...data,
          showTitle: !(['creatorAvatar', 'divider'].includes(data.key) || ['richEditor', 'upAttachment'].includes(data.type)),
          titleStyle: [],
          titleWrap: false,
          emptyVisible: false,
          defaultValue: '',
          gridType: !['divider'].includes(data.key) && !['richEditor', 'upAttachment'].includes(data.type) ? 8 : 24,
          showType: 'text',
          fontLength: 50,
          fontSize: 12,
          avatarSize: 42,
          fontColor: '#333',
          tagColor: '',
          textAlign: 'left',
          verticalAlign: 'middle',
          margin: {
            top: 0,
            bottom: 0
          },
          padding: {
            top: 0,
            left: 0,
            right: 0,
            bottom: 0
          },
          radius: {
            topLeft: 0,
            topRight: 0,
            bottomLeft: 0,
            bottomRight: 0
          },
          borderStyle: '',
          borderVisible: [],
          optionsHide: [],
          dividerDirection: 0,
          dividerWidth: 1,
          dividerColor: '#EBEEFD',
          dividerStyle: 'solid'
        });
      } else {
        // 分割线取消勾选直接删除字段配置项
        if (data.key.startsWith('divider') && data.key !== 'divider') this.updateCardFields(data, true);
        if (this.activeKey === data.key) this.activeKey = '';
        this.$nextTick(() => {
          this.cardConfigsData.options = this.cardConfigsData.options.filter(i => i.key !== data.key);
          if (!this.cardConfigsData.options.length) this.cardConfigsData.isEnable = false;
        });
      }
    }
  }
};
</script>

<style scoped lang="scss">
.card-setting-container {
  display: flex;
  justify-content: space-between;
  height: calc(100vh - 156px);
  transform: translateY(-11px);
  .left-box {
    flex-shrink: 0;
    flex-basis: 330px;
    box-shadow: 5px 0 6px 0 rgb(240 242 245 / 81%);
    padding-right: 10px;
    height: calc(100vh - 130px);
    .field-group {
      max-height: calc(100vh - 180px);
      display: flex;
      flex-wrap: wrap;
      border-top: 1px solid #EBEEFD;
      border-left: 1px solid #EBEEFD;
      width: 320px;
      @include scrollBar($x: hidden, $y: auto, $width: 4px);
      .field-item {
        position: relative;
        display: flex;
        align-items: center;
        border-bottom: 1px solid #EBEEFD;
        border-right: 1px solid #EBEEFD;
        width: 50%;
        height: 47px;
        padding: 0 17px;
        background-color: #fff;
        overflow: hidden;
        .check {
          margin-right: 8px;
        }
        .field-content {
          display: flex;
          overflow: hidden;
          align-items: center;
          flex: 1;
          font-size:14px;
          color: rgba(20,28,61,1);
          line-height: 1.2;
        }
        &:hover {
          background-color: #FAFAFA;
        }
      }
    }
  }
  .middle-box {
    flex: 1;
    padding: 10px;
    @include scrollBar($x: auto, $y: auto, $width: 8px);
    .card-action-btns {
      margin: 24px 0 12px;
      justify-content: center;
      > div {
        margin-right: 24px;
      }
    }
    ::v-deep {
      .card-view-box {
        margin: 12px auto;
      }
    }
  }
  .right-box {
    height: calc(100vh - 130px);
    flex-basis: 180px;
    flex-shrink: 0;
    box-shadow: -5px 0 6px 0 rgb(240 242 245 / 81%);
    padding-left: 10px;
    z-index: 1;
    .tip-text {
      color: #999;
      font-size: 12px;
      font-weight: normal;
      margin-left: 6px;
    }
  }
}
</style>
